/**
 * 规则管理模块
 * 处理代理规则相关的业务逻辑
 */
export class RulesManager {
  constructor(dbCore) {
    this.db = dbCore;
    this.initStatements();
  }

  /**
   * 初始化预编译语句
   */
  initStatements() {
    // 保存规则的预编译语句
    this.saveRuleStmt = this.db.prepare(`
      INSERT OR REPLACE INTO rules 
      (id, name, description, enabled, conditions, actions, createdAt, updatedAt)
      VALUES (?, ?, ?, ?, ?, ?, ?, ?)
    `);

    // 查询所有规则的预编译语句
    this.getRulesStmt = this.db.prepare(`
      SELECT id, name, description, enabled, conditions, actions, createdAt, updatedAt
      FROM rules
      ORDER BY createdAt DESC
    `);

    // 查询启用规则的预编译语句
    this.getEnabledRulesStmt = this.db.prepare(`
      SELECT id, name, description, enabled, conditions, actions, createdAt, updatedAt
      FROM rules
      WHERE enabled = 1
      ORDER BY createdAt DESC
    `);

    // 查询单个规则的预编译语句
    this.getRuleStmt = this.db.prepare(`
      SELECT id, name, description, enabled, conditions, actions, createdAt, updatedAt
      FROM rules
      WHERE id = ?
    `);

    // 删除规则的预编译语句
    this.deleteRuleStmt = this.db.prepare(`
      DELETE FROM rules WHERE id = ?
    `);

    // 更新规则状态的预编译语句
    this.updateRuleStatusStmt = this.db.prepare(`
      UPDATE rules SET enabled = ?, updatedAt = ? WHERE id = ?
    `);
  }

  /**
   * 保存规则
   */
  saveRule(rule) {
    try {
      const now = Date.now();
      const ruleData = {
        id: rule.id,
        name: rule.name,
        description: rule.description || '',
        enabled: rule.enabled ? 1 : 0,
        conditions: JSON.stringify(rule.conditions || []),
        actions: JSON.stringify(rule.actions || []),
        createdAt: rule.createdAt || now,
        updatedAt: now
      };

      this.saveRuleStmt.run(
        ruleData.id,
        ruleData.name,
        ruleData.description,
        ruleData.enabled,
        ruleData.conditions,
        ruleData.actions,
        ruleData.createdAt,
        ruleData.updatedAt
      );

      console.log(`📚 已保存规则: ${rule.name}`);
      return true;
    } catch (error) {
      console.error('❌ 保存规则失败:', error.message);
      return false;
    }
  }

  /**
   * 获取所有规则
   */
  getRules() {
    try {
      const rows = this.getRulesStmt.all();
      return rows.map(this.transformRowToRule.bind(this));
    } catch (error) {
      console.error('❌ 获取规则列表失败:', error.message);
      return [];
    }
  }

  /**
   * 获取启用的规则
   */
  getEnabledRules() {
    try {
      const rows = this.getEnabledRulesStmt.all();
      return rows.map(this.transformRowToRule.bind(this));
    } catch (error) {
      console.error('❌ 获取启用规则失败:', error.message);
      return [];
    }
  }

  /**
   * 获取单个规则
   */
  getRule(id) {
    try {
      const row = this.getRuleStmt.get(id);
      if (!row) {
        return null;
      }
      return this.transformRowToRule(row);
    } catch (error) {
      console.error('❌ 获取规则失败:', error.message);
      return null;
    }
  }

  /**
   * 删除规则
   */
  deleteRule(id) {
    try {
      const result = this.deleteRuleStmt.run(id);
      const success = result.changes > 0;
      
      if (success) {
        console.log(`📚 已删除规则: ${id}`);
      } else {
        console.warn(`⚠️ 未找到要删除的规则: ${id}`);
      }
      
      return success;
    } catch (error) {
      console.error('❌ 删除规则失败:', error.message);
      return false;
    }
  }

  /**
   * 启用/禁用规则
   */
  updateRuleStatus(id, enabled) {
    try {
      const result = this.updateRuleStatusStmt.run(
        enabled ? 1 : 0,
        Date.now(),
        id
      );
      
      const success = result.changes > 0;
      
      if (success) {
        console.log(`📚 已${enabled ? '启用' : '禁用'}规则: ${id}`);
      } else {
        console.warn(`⚠️ 未找到要更新的规则: ${id}`);
      }
      
      return success;
    } catch (error) {
      console.error('❌ 更新规则状态失败:', error.message);
      return false;
    }
  }

  /**
   * 将数据库行转换为规则对象
   */
  transformRowToRule(row) {
    return {
      id: row.id,
      name: row.name,
      description: row.description,
      enabled: Boolean(row.enabled),
      conditions: this.safeJsonParse(row.conditions, []),
      actions: this.safeJsonParse(row.actions, []),
      createdAt: row.createdAt,
      updatedAt: row.updatedAt
    };
  }

  /**
   * 安全的JSON解析
   */
  safeJsonParse(jsonString, defaultValue = null) {
    try {
      return jsonString ? JSON.parse(jsonString) : defaultValue;
    } catch (error) {
      console.warn('⚠️ JSON解析失败:', error.message);
      return defaultValue;
    }
  }

  /**
   * 批量导入规则
   */
  importRules(rules) {
    try {
      const importTransaction = this.db.transaction(() => {
        let successCount = 0;
        let errorCount = 0;

        for (const rule of rules) {
          try {
            this.saveRule(rule);
            successCount++;
          } catch (error) {
            console.error(`❌ 导入规则失败 [${rule.name}]:`, error.message);
            errorCount++;
          }
        }

        return { successCount, errorCount };
      });

      const result = importTransaction();
      console.log(`📚 规则导入完成: 成功 ${result.successCount} 条，失败 ${result.errorCount} 条`);
      return result;
    } catch (error) {
      console.error('❌ 批量导入规则失败:', error.message);
      return { successCount: 0, errorCount: rules.length };
    }
  }

  /**
   * 导出规则
   */
  exportRules() {
    try {
      const rules = this.getRules();
      return {
        exportedAt: Date.now(),
        version: '1.0',
        count: rules.length,
        rules: rules
      };
    } catch (error) {
      console.error('❌ 导出规则失败:', error.message);
      return null;
    }
  }

  /**
   * 搜索规则
   */
  searchRules(searchOptions = {}) {
    const {
      name = '',
      enabled = null,
      hasConditions = null,
      hasActions = null
    } = searchOptions;

    let sql = `
      SELECT id, name, description, enabled, conditions, actions, createdAt, updatedAt
      FROM rules
      WHERE 1=1
    `;

    const params = [];

    if (name) {
      sql += ' AND name LIKE ?';
      params.push(`%${name}%`);
    }

    if (enabled !== null) {
      sql += ' AND enabled = ?';
      params.push(enabled ? 1 : 0);
    }

    if (hasConditions !== null) {
      if (hasConditions) {
        sql += ` AND conditions != '[]' AND conditions IS NOT NULL`;
      } else {
        sql += ` AND (conditions = '[]' OR conditions IS NULL)`;
      }
    }

    if (hasActions !== null) {
      if (hasActions) {
        sql += ` AND actions != '[]' AND actions IS NOT NULL`;
      } else {
        sql += ` AND (actions = '[]' OR actions IS NULL)`;
      }
    }

    sql += ' ORDER BY createdAt DESC';

    try {
      const stmt = this.db.prepare(sql);
      const rows = stmt.all(...params);
      return rows.map(this.transformRowToRule.bind(this));
    } catch (error) {
      console.error('❌ 搜索规则失败:', error.message);
      return [];
    }
  }

  /**
   * 获取规则统计信息
   */
  getRuleStats() {
    try {
      const stats = {};

      // 总规则数
      const totalCount = this.db.prepare('SELECT COUNT(*) as count FROM rules').get();
      stats.totalRules = totalCount.count;

      // 启用的规则数
      const enabledCount = this.db.prepare('SELECT COUNT(*) as count FROM rules WHERE enabled = 1').get();
      stats.enabledRules = enabledCount.count;

      // 禁用的规则数
      stats.disabledRules = stats.totalRules - stats.enabledRules;

      // 有条件的规则数
      const withConditionsCount = this.db.prepare(`
        SELECT COUNT(*) as count FROM rules 
        WHERE conditions != '[]' AND conditions IS NOT NULL
      `).get();
      stats.rulesWithConditions = withConditionsCount.count;

      // 有动作的规则数
      const withActionsCount = this.db.prepare(`
        SELECT COUNT(*) as count FROM rules 
        WHERE actions != '[]' AND actions IS NOT NULL
      `).get();
      stats.rulesWithActions = withActionsCount.count;

      return stats;
    } catch (error) {
      console.error('❌ 获取规则统计失败:', error.message);
      return {};
    }
  }

  /**
   * 清空所有规则
   */
  clearAllRules() {
    try {
      const result = this.db.prepare('DELETE FROM rules').run();
      console.log(`📚 已清空所有规则，删除了 ${result.changes} 条记录`);
      return result.changes;
    } catch (error) {
      console.error('❌ 清空规则失败:', error.message);
      return 0;
    }
  }

  /**
   * 复制规则
   */
  duplicateRule(ruleId, newName) {
    try {
      const originalRule = this.getRule(ruleId);
      if (!originalRule) {
        console.warn(`⚠️ 未找到要复制的规则: ${ruleId}`);
        return null;
      }

      const newRule = {
        ...originalRule,
        id: `rule_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
        name: newName || `${originalRule.name} (副本)`,
        createdAt: Date.now(),
        updatedAt: Date.now()
      };

      const success = this.saveRule(newRule);
      if (success) {
        console.log(`📚 已复制规则: ${newRule.name}`);
        return newRule;
      }

      return null;
    } catch (error) {
      console.error('❌ 复制规则失败:', error.message);
      return null;
    }
  }
} 